﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Dal.Models;
using Framework.Common;
using Dal.Entities;
using Framework.Common.LinqExtention;
namespace Web.Controllers
{
    [MyAuthAttribute(Role = 0)]
    [ValidateInput(false)]
    public class DocController : Controller
    {
        int doctype;
        int docid;
        string status = string.Empty;
        Framework.Data.IRepository rep;

        public DocController()
        {
            rep = Framework.Data.RepositoryFactory.GetRepository();
            //docid
            docid = TypeConvertHelper.StrToInt(System.Web.HttpContext.Current.Request["docid"], 0);
            ViewBag.DocID = docid;
            //doc type
            doctype = Common.DocType();
            ViewBag.DocType = doctype;

            ViewBag.Status = System.Web.HttpContext.Current.Request["status"] ?? "edit";

            //Dal.Entities.Doc doc = rep.GetByKey<Doc>(docid);
        }

        private IList<MEET> QueryMeet(QueryModel query)
        {
            using (MessageContext db = new MessageContext())
            {
                IQueryable<MEET> list = db.MEETs;
                Expression<Func<MEET, bool>> exp = m => true;
                if (!string.IsNullOrWhiteSpace(query.Type))
                {
                    exp = exp.And(i => i.TYPE == query.Type);
                }
                if (!Common.Admin())
                {
                    string phone = Common.GetPhone();
                    exp = exp.And(i => i.PHONE == phone);
                }
                if (!string.IsNullOrWhiteSpace(query.City))
                {
                    var array = query.City.Split(new[] { ',', ' ', '，' }, StringSplitOptions.RemoveEmptyEntries);
                    Expression<Func<MEET, bool>> tmp = null;
                    foreach (var s in array)
                    {
                        if (tmp == null)
                        {
                            tmp = i => i.CONTENT.Contains(s);
                        }
                        else
                        {
                            tmp = tmp.Or(i => i.CONTENT.Contains(s));
                        }
                    }
                    exp = exp.And(tmp);
                }
                if (!string.IsNullOrWhiteSpace(query.Department))
                {
                    var array = query.Department.Split(new[] { ',', ' ', '，' }, StringSplitOptions.RemoveEmptyEntries);
                    Expression<Func<MEET, bool>> tmp = null;
                    foreach (var s in array)
                    {
                        if (tmp == null)
                        {
                            tmp = i => i.CONTENT.Contains(s);
                        }
                        else
                        {
                            tmp = tmp.Or(i => i.CONTENT.Contains(s));
                        }
                    }
                    exp = exp.And(tmp);
                    //list = list.Where(i => i.CONTENT.Contains(query.Department));
                }
                if (!string.IsNullOrWhiteSpace(query.Hospital))
                {
                    var array = query.Hospital.Split(new[] { ',', ' ', '，' }, StringSplitOptions.RemoveEmptyEntries);
                    Expression<Func<MEET, bool>> tmp = null;
                    foreach (var s in array)
                    {
                        if (tmp == null)
                        {
                            tmp = i => i.CONTENT.Contains(s);
                        }
                        else
                        {
                            tmp = tmp.Or(i => i.CONTENT.Contains(s));
                        }
                    }
                    exp = exp.And(tmp);
                    //list = list.Where(i => i.CONTENT.Contains(query.Hospital));
                }
                if (!string.IsNullOrWhiteSpace(query.Product))
                {
                    var array = query.Product.Split(new[] { ',', ' ', '，' }, StringSplitOptions.RemoveEmptyEntries);
                    Expression<Func<MEET, bool>> tmp = null;
                    foreach (var s in array)
                    {
                        if (tmp == null)
                        {
                            tmp = i => i.CONTENT.Contains(s);
                        }
                        else
                        {
                            tmp = tmp.Or(i => i.CONTENT.Contains(s));
                        }
                    }
                    exp = exp.And(tmp);
                    //list = list.Where(i => i.CONTENT.Contains(query.Product));
                }
                if (!string.IsNullOrWhiteSpace(query.Province))
                {
                    var array = query.Province.Split(new[] { ',', ' ', '，' }, StringSplitOptions.RemoveEmptyEntries);
                    Expression<Func<MEET, bool>> tmp = null;
                    foreach (var s in array)
                    {
                        if (tmp == null)
                        {
                            tmp = i => i.CONTENT.Contains(s);
                        }
                        else
                        {
                            tmp = tmp.Or(i => i.CONTENT.Contains(s));
                        }
                    }
                    exp = exp.And(tmp);
                    //list = list.Where(i => i.CONTENT.Contains(query.Province));
                }
                if (query.InputStart0.HasValue)
                {
                    exp = exp.And(i => query.InputStart0.Value <= Convert.ToDateTime(i.STARTTIME));
                }
                if (query.InputStart1.HasValue)
                {
                    exp = exp.And(i => query.InputStart1.Value >= Convert.ToDateTime(i.STARTTIME));
                }
                if (query.InputEnd0.HasValue)
                {
                    exp = exp.And(i => query.InputEnd0.Value <= Convert.ToDateTime(i.ENDTIME));
                }
                if (query.InputEnd1.HasValue)
                {
                    exp = exp.And(i => query.InputEnd1.Value >= Convert.ToDateTime(i.ENDTIME));
                }
                return list.Where(exp).ToList();
            }
        }


        public ActionResult Manage()
        {
            QueryModel query = new QueryModel();
            TryUpdateModel(query);
            int pageindex = TypeConvertHelper.StrToInt(Request["pageindex"], 1);
            ViewBag.Record = QueryMeet(query);
            return View(query);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult Export()
        {
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            QueryModel query = new QueryModel();
            TryUpdateModel(query);
            var list = QueryMeet(query);
            NPOI.SS.UserModel.IWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook();
            var sheet = book.CreateSheet("export");
            var rowTitle = sheet.CreateRow(0);
            var cellTitle0 = rowTitle.CreateCell(0);
            var cellTitle1 = rowTitle.CreateCell(1);
            var cellTitle2 = rowTitle.CreateCell(2);
            var cellTitle3 = rowTitle.CreateCell(3);
            var cellTitle4 = rowTitle.CreateCell(4);
            var cellTitle5 = rowTitle.CreateCell(5);
            var cellTitle6 = rowTitle.CreateCell(6);
            var cellTitle7 = rowTitle.CreateCell(7);
            var cellTitle8 = rowTitle.CreateCell(8);
            var cellTitle9 = rowTitle.CreateCell(9);

            cellTitle0.SetCellValue("会议编号");
            cellTitle1.SetCellValue("开通电话");
            cellTitle2.SetCellValue("产品");
            cellTitle3.SetCellValue("省份");
            cellTitle4.SetCellValue("城市");
            cellTitle5.SetCellValue("医院");
            cellTitle6.SetCellValue("科室");
            cellTitle7.SetCellValue("开始时间");
            cellTitle8.SetCellValue("结束时间");
            cellTitle9.SetCellValue("参加人数");

            int index = 1;
            foreach (var meet in list)
            {
                var row = sheet.CreateRow(index);
                var cell0 = row.CreateCell(0);
                var cell1 = row.CreateCell(1);
                var cell2 = row.CreateCell(2);
                var cell3 = row.CreateCell(3);
                var cell4 = row.CreateCell(4);
                var cell5 = row.CreateCell(5);
                var cell6 = row.CreateCell(6);
                var cell7 = row.CreateCell(7);
                var cell8 = row.CreateCell(8);
                var cell9 = row.CreateCell(9);

                cell0.SetCellValue(meet.NUM);
                cell1.SetCellValue(meet.PHONE);
                cell2.SetCellValue(Split(meet.CONTENT, 4));
                cell3.SetCellValue(Split(meet.CONTENT, 0));
                cell4.SetCellValue(Split(meet.CONTENT, 1));
                cell5.SetCellValue(Split(meet.CONTENT, 2));
                cell6.SetCellValue(Split(meet.CONTENT, 3));
                cell7.SetCellValue(meet.STARTTIME);
                cell8.SetCellValue(meet.ENDTIME);
                cell9.SetCellValue(meet.ANUM);

                index++;
            }
            var bytes = new byte[] { };
            using (var ms = new MemoryStream())
            {
                book.Write(ms);
                bytes = ms.ToArray();
            }

            return File(bytes, contentType);
        }


        public ActionResult Detail()
        {
            string id = Request["id"];
            if (!string.IsNullOrWhiteSpace(id))
            {
                using (MessageContext db = new MessageContext())
                {
                    var list = db.MEETLISTs.Where(i => i.NUM == id).ToList();
                    ViewBag.Record = list;
                    return View();
                }
            }
            return new EmptyResult();
        }


        public ActionResult DetailExport()
        {
            string id = Request["id"];
            if (!string.IsNullOrWhiteSpace(id))
            {
                string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                List<MEETLIST> list;
                using (MessageContext db = new MessageContext())
                {
                    list = db.MEETLISTs.Where(i => i.NUM == id).ToList();
                }
                NPOI.SS.UserModel.IWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook();
                var sheet = book.CreateSheet(id);
                var rowTitle = sheet.CreateRow(0);
                var cellTitle0 = rowTitle.CreateCell(0);
                var cellTitle1 = rowTitle.CreateCell(1);
                var cellTitle2 = rowTitle.CreateCell(2);
                var cellTitle3 = rowTitle.CreateCell(3);
                var cellTitle4 = rowTitle.CreateCell(4);


                cellTitle0.SetCellValue("会议编号");
                cellTitle1.SetCellValue("参与电话");
                cellTitle2.SetCellValue("答案");
                cellTitle3.SetCellValue("参与时间");
                cellTitle4.SetCellValue("是否中奖");


                int index = 1;
                foreach (var meet in list)
                {
                    var row = sheet.CreateRow(index);
                    var cell0 = row.CreateCell(0);
                    var cell1 = row.CreateCell(1);
                    var cell2 = row.CreateCell(2);
                    var cell3 = row.CreateCell(3);
                    var cell4 = row.CreateCell(4);

                    cell0.SetCellValue(meet.NUM);
                    cell1.SetCellValue(meet.PHONE);
                    cell2.SetCellValue(meet.ANSER);
                    cell3.SetCellValue(meet.RTIME);
                    cell4.SetCellValue(meet.ZJ);

                    index++;
                }
                var bytes = new byte[] { };
                using (var ms = new MemoryStream())
                {
                    book.Write(ms);
                    bytes = ms.ToArray();
                }

                return File(bytes, contentType, id);
            }
            return new EmptyResult();
        }



        #region excel 导出
        private void ResponseExcel()
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + ".xls");
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-excel";
        }

        #endregion

        string Split(string content, int index)
        {
            if (!string.IsNullOrWhiteSpace(content))
            {
                string[] arr = content.Split(',');
                if (arr.Length >= index + 1)
                {
                    return arr[index];
                }
            }
            return string.Empty;
        }











    }
    #region entity
    /// <summary>
    /// 
    /// </summary>
    public class QueryModel
    {
        public string Province { get; set; }
        public string City { get; set; }
        public string Hospital { get; set; }
        public string Department { get; set; }
        public string Product { get; set; }
        public DateTime? InputStart0 { get; set; }
        public DateTime? InputStart1 { get; set; }
        public DateTime? InputEnd0 { get; set; }
        public DateTime? InputEnd1 { get; set; }
        public string UserName { get; set; }
        public string Type { get; set; }
    }
    /// <summary>
    /// 
    /// </summary>
    public class DocForShow
    {
        public Doc doc { get; set; }
        public string username { get; set; }

        #region export

        public DocCommon doc0 { get; set; }
        public Doc1 doc1 { get; set; }
        public Doc2 doc2 { get; set; }
        public Doc3 doc3 { get; set; }
        public Doc4 doc4 { get; set; }

        #endregion
    }

    #endregion
}
